package com.eh.erd.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.eh.erd.oss.service.FileService;
import com.eh.erd.oss.util.OssProperties;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.UUID;

/**
 * @author zhuyuanwei
 * @version 1.0
 * @date 2021/5/13 10:49
 */
@Service
public class FileServiceImpl implements FileService {
    @Override
    public String upload(InputStream inputStream, String module, String fileName) {
        OSS ossClient = new OSSClientBuilder().build(
                OssProperties.ENDPOINT,
                OssProperties.KEY_ID,
                OssProperties.KEY_SECRET);
        if(!ossClient.doesBucketExist(OssProperties.BUCKET_NAME)){
            ossClient.createBucket(OssProperties.BUCKET_NAME);
            ossClient.setBucketAcl(OssProperties.BUCKET_NAME, CannedAccessControlList.PublicRead);
        }

        String dataTime=new DateTime().toString("yyyy/MM/dd");
        fileName= UUID.randomUUID().toString()+fileName.substring(fileName.lastIndexOf("."));
        String key=module+"/"+dataTime+"/"+fileName;
        ossClient.putObject(OssProperties.BUCKET_NAME, key, inputStream);

        return "https://"+OssProperties.BUCKET_NAME+"."+OssProperties.ENDPOINT+"/"+key;
    }

    @Override
    public void removeFile(String url) {
        OSS ossClient = new OSSClientBuilder().build(
                OssProperties.ENDPOINT,
                OssProperties.KEY_ID,
                OssProperties.KEY_SECRET);
        String bucketName="https://"+OssProperties.BUCKET_NAME+"."+OssProperties.ENDPOINT+"/";
        String objectName=url.substring(bucketName.length());
        if(ossClient.doesBucketExist(OssProperties.BUCKET_NAME)){
            ossClient.deleteObject(OssProperties.BUCKET_NAME, objectName);
        }
        ossClient.shutdown();
    }
}
